package com.example.testcoroutine

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query

// bean and net files
data class ProjectResponse(
    val data: Data
)

data class Data(
    val curPage: Int,
    val datas: List<Project>,
    val pageCount: Int
)

data class Project(
    val author: String,
    val envelopePic: String,
    val title: String,
    val niceDate: String,
    val desc: String
)

object ServiceCreator {
    private const val BASE_URL = "https://www.wanandroid.com"
    private val retrofit = Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(
        GsonConverterFactory.create()
    ).build()

    fun <T> create(serviceClass: Class<T>): T = retrofit.create(serviceClass)
    inline fun <reified T> create(): T = create(T::class.java)
}

interface ProjectService {
    @GET("/project/list/{page}/json")
    suspend fun getProjects(@Path("page") page: Int, @Query("cid") id: Int): ProjectResponse
}

object Repository {
    suspend fun getProjects(page: Int, id: Int): ProjectResponse {
        return withContext(Dispatchers.IO) {
            ServiceCreator.create<ProjectService>().getProjects(page, id)
        }
    }
}

class ProjectPagingSource(private val repository: Repository) : PagingSource<Int, Project>() {
    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Project> {
        return try {
            val nextPage = params.key ?: 1
            val response = repository.getProjects(nextPage, 294)
            LoadResult.Page(
                data = response.data.datas,
                prevKey = if (nextPage == 1) null else nextPage - 1,
                nextKey = if (nextPage < response.data.pageCount) nextPage + 1 else null
            )
        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }

    override fun getRefreshKey(state: PagingState<Int, Project>): Int? {
        return null
    }
}


